﻿using System;
using System.Threading.Tasks;
using KL.UFrame.Core.Configuration;
using KL.UFrame.Core.Exception;
using KL.UFrame.Data.Entities;

namespace KL.UFrame.Data.Business.Impl
{
    public class EmailBusiness:BusinessBase,IEmailBusiness
    {
        public async Task<int> CreateDbEmailAsync(EmailRecord email)
        {
            email.CreateTime = DateTime.Now;
            email.Status = "待发送";
            Db.EmailRecords.Add(email);
            return await Db.SaveChangesAsync();
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="recipients"></param>
        /// <param name="code"></param>
        public async Task<int> SendVerifyCodeAsync(string recipients, string code)
        {
            var email = new EmailRecord
            {
                Sender = AppConfiguration.AppName,
                Subject = AppConfiguration.AppName + "平台验证码",
                Recipients = recipients,
                Body = "<p>尊敬的客户：</p>"
                       + "<p style='text-indent:2em'>您好！<p>"
                       + "<p style='text-indent:2em'>您的验证码为：" + code + "<p>"
                       + "<p style='text-indent:2em;margin-top:30px;'>若不是您本人在操作，请忽略本邮件！<p>"
                       + "<p style='text-indent:2em;margin-top:40px;'>" + AppConfiguration.AppName + "<p>"

            };
            return await CreateDbEmailAsync(email);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="recipients"></param>
        /// <returns>返回验证码</returns>
        public async Task<int> SendVerifyCodeAsync(string recipients)
        {
            var cacheKey = GetTokenCacheKeys(recipients);
            var token = Cache.Get<string>(cacheKey);

            if (token != null)
            {
                throw new ResultException(-100, "操作过于频繁");
            }

            var code = GenerateValidateCode();
            var result = await SendVerifyCodeAsync(recipients, code.ToString());
            if (result > 0)
            {
                Cache.Add(cacheKey, code.ToString());
                Cache.Expire(cacheKey, TimeSpan.FromMinutes(5));
                return code;
            }
            return -1;
        }

        private string GetTokenCacheKeys(string recipients)
        {
            return "TokenCacheKeys_" + recipients;
        }

        public string GetValidateCode(string recipients)
        {
            var cacheKey = GetTokenCacheKeys(recipients);
            return Cache.Get<string>(cacheKey);
        }

        static Random _random = new Random((int)DateTime.Now.Ticks);
        static int GenerateValidateCode(int length = 6)
        {
            int min = (int)Math.Pow(10, length - 1);
            int max = (int)Math.Pow(10, length) - 1;
            return _random.Next(min, max);
        }
    }
}